package sql

import (
	"gitee.com/yxd1990/golang-common/debug"
	"gitee.com/yxd1990/golang-common/errors"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

type TxFunc func(o orm.Ormer) error

func InTx(txFunc TxFunc, ormObj ...orm.Ormer) (err error) {
	var o orm.Ormer
	if len(ormObj) == 0 {
		o = orm.NewOrm()
		err = o.Begin()
		defer func() {
			if re := recover(); re != nil {
				logs.Error("InTx panic error : %#v,%s", re, debug.GetStackInfo())
				if err == nil {
					err = errors.Emit("系统异常Panic")
				}
			}
			if err == nil {
				err = o.Commit()
			}
			if err != nil {
				_ = o.Rollback()
			}
		}()
		if err != nil {
			return
		}
	} else {
		o = ormObj[0]
	}
	err = txFunc(o)
	return
}

func ParseNoRowsErr(err error) error {
	if err == orm.ErrNoRows {
		err = errors.Emit("纪录不存在，请刷新再试")
	}
	return err
}
